import { SERVICES } from '@/common';
import moment from 'moment';
import FormCommon from '@/components/FormCommon';
import AvatarCom from '@/components/avatarUpload';
import CommonTable from '@/components/commonTable';
import { IFilterParams } from '@/components/commonTable/interface';
import { add, deleted, getCurrent, update } from '@/services/api/user';
import {
	DrawerForm,
	PageContainer,
	ProForm,
	ProFormSelect,
	ProFormText,
} from '@ant-design/pro-components';
import { history, useModel } from '@umijs/max';
import { useRequest } from 'ahooks-v3';
import {
	Avatar,
	Form,
	InputNumber,
	Popconfirm,
	Space,
	Tag,
	message,
} from 'antd';
import { useForm } from 'antd/es/form/Form';
import TextArea from 'antd/es/input/TextArea';
import React from 'react';

export interface IVipProps {
	[key: string]: any;
}
const FILTER_CONDITION: IFilterParams = {
	keywords: '',
	currentPage: 1,
	pageSize: 10,
};
const Vip: React.FC<IVipProps> = () => {
	// 获取当前用户的身份信息
	const { initialState = {} } = useModel('@@initialState');
	const {
		userInfo: { role, city, province },
	} = initialState || {};

	const [isVisible, setIsVisible] = React.useState<boolean>(false); // 用于展示新增 modal 框的展示
	const [form] = useForm();
	const [editForm] = useForm();
	const [isEdit, setIsEdit] = React.useState<boolean>(false);
	const {
		loading,
		data,
		run: getListRun,
	} = useRequest((params) => getCurrent(params), {
		manual: true,
	});

	const [filterCondition, setFilterCondition] = React.useState<IFilterParams>(
		FILTER_CONDITION || {
			keywords: '',
			currentPage: 1,
			pageSize: 10,
		},
	);

	const highLightText = React.useCallback(
		(text: string) => {
			const theKeyword = filterCondition.keywords;
			if (!theKeyword || !theKeyword.trim()) return text;
			return text.split(theKeyword).map((te, index) => {
				if (index === 0) return te;
				return [
					<span style={{ color: '#FF8800' }}>{theKeyword}</span>,
					<span>{te}</span>,
				];
			});
		},
		[filterCondition.keywords],
	);

	// 点击新增按钮
	const onHandleAdd = () => {
		form.resetFields();
		setIsVisible(true);
	};

	// 批量删除
	const onDelete = async (
		rowKeys: React.Key[],
		rows: Record<string, any>[],
	) => {
		try {
			const res = await deleted(rowKeys as number[]);
			if (res.status !== 200) {
				return message.error(res.message || '删除失败');
			}
			message.success('删除成功');
		} catch (error) {
			console.log('error', error);
		} finally {
			setFilterCondition({ ...FILTER_CONDITION });
		}
	};

	React.useEffect(() => {
		getListRun({ ...filterCondition, role: 'vip', city });
	}, [filterCondition, role, city, getListRun]);

	// 页面table的数据
	const columns = [
		{
			title: '头像',
			key: 'cover',
			dataIndex: 'cover',
			render: (_, record: any) => (
				<Avatar
					alt="头像"
					size={60}
					style={{ verticalAlign: 'middle', border: '1px solid #f0f0f0' }}
					src={
						record.cover
							? SERVICES + record.cover
							: SERVICES + '/vehicle/BiazfanxmamNRoxxVxka.png'
					}
				/>
			),
		},
		{
			title: '名称',
			key: 'name',
			dataIndex: 'name',
			render: (_, record) => <span>{highLightText(record.name || '_')}</span>,
		},
		{
			title: '昵称',
			key: 'nickname',
			dataIndex: 'nickname',
			render: (_, record) => <span>{record.nickname || '_'}</span>,
		},
		{
			title: '省份',
			key: 'province',
			dataIndex: 'province',
		},
		{
			title: '城市',
			key: 'city',
			dataIndex: 'city',
		},
		{
			title: '角色',
			key: 'role',
			dataIndex: 'role',
			render: (_, record) => (
				<span>
					{record.role === 'vip' ? (
						<Tag color="green">Vip用户</Tag>
					) : record.role === 'normal' ? (
						<Tag color="geekblue">普通用户</Tag>
					) : (
						<Tag color="orange">商家</Tag>
					)}
				</span>
			),
		},
		{
			title: '账户',
			key: 'account',
			dataIndex: 'account',
		},

		{
			title: '更新时间',
			key: 'updateDate',
			dataIndex: 'updated_date',
			render: (_, record) => <span>{record.updated_date && moment(record.updated_date).format('YYYY-MM-DD HH:mm:ss') || '-'}</span>,
		},
		{
			title: '操作',
			key: 'operator',
			render: (_, record: any) => {
				return (
					<Space size="middle">
						<a
							onClick={() => {
								history.push('/detail/' + record.id, record.type || 'user');
							}}
						>
							详情
						</a>
						<a
							onClick={() => {
								editForm.setFieldsValue(record);
								setIsEdit(true);
							}}
						>
							编辑
						</a>
						<Popconfirm
							title="删除"
							description="删除后不可恢复，是否确定删除?"
							placement="topRight"
							onConfirm={async () => {
								const res = await deleted([record.id]);
								if (res.status !== 200) {
									return message.error(res.message || '删除失败');
								}
								message.success('删除成功');
								setFilterCondition({ ...FILTER_CONDITION });
							}}
							okText="确定"
							cancelText="取消"
						>
							<a style={{ color: 'red' }}>删除</a>
						</Popconfirm>
					</Space>
				);
			},
		},
	];

	// 添加的表单项
	const editFormItems = [
		{
			title: '姓名',
			dataIndex: 'name',
			width: 'm',
			formItemProps: {
				rules: [
					{
						required: true,
						message: '此项为必填项',
					},
				],
			},
		},
		{
			title: '密码',
			dataIndex: 'password',
			valueType: 'password',
			width: 'm',
			formItemProps: {
				rules: [
					{
						required: true,
						message: '此项为必填项',
					},
				],
			},
		},
		{
			title: '省份',
			initialValues: province,
			dataIndex: 'province',
			width: 'm',
			formItemProps: {
				rules: [
					{
						required: true,
						message: '此项为必填项',
					},
				],
			},
		},
		{
			title: '城市',
			dataIndex: 'city',
			width: 'm',
			request: async()=>{
				return new Promise((resolve, reject) =>{
					resolve([
						{
							value:'成都',
							label: '成都'
						}
					])
				})
			},
			formItemProps: {
				rules: [
					{
						required: true,
						message: '此项为必填项',
					},
				],
			},
		},
		{
			title: '电话',
			dataIndex: 'phone',
			width: 'm',
			formItemProps: {
				rules: [
					{
						required: true,
						message: '此项为必填项',
					},
					{
						required: true,
						message: '无效的电话号码',
						pattern: /^1[3-9]\d{9}$/,
						validateTrigger: 'onSubmit',
					},
				],
			},
		},
		{
			title: '角色',
			dataIndex: 'role',
			initialValue: 'vip',
			width: 'm',
			valueEnum: {
				vip: {
					text: 'vip用户',
					status: 'vip',
				},
			},
			formItemProps: {
				rules: [
					{
						required: true,
						message: '此项为必填项',
					},
				],
			},
		},
	];

	return (
		<div>
			<PageContainer>
				<CommonTable
					isSticky
					loading={loading}
					columns={columns}
					total={data?.data?.total}
					dataSource={data?.data?.list}
					filterCondition={filterCondition}
					setFilter={setFilterCondition}
					isPagination={data?.total}
					onDelete={onDelete}
					isRowSelection
					onAdd={onHandleAdd}
				/>
			</PageContainer>

			{/* 弹窗 */}
			<FormCommon
				isOpen={isVisible}
				title="新增vip用户"
				layoutFormType="ModalForm"
				layout="horizontal"
				formInstance={form}
				setIsOpen={setIsVisible}
				width={400}
				onChange={async (values) => {
					const res = await add(values);
					if (res.status !== 200) {
						return message.error(res.message || '新增失败');
					}
					message.success('新增成功');
					setFilterCondition({ ...FILTER_CONDITION });
					setIsVisible(false);
				}}
				formColumn={editFormItems}
			/>

			{/* 编辑弹框 */}
			<DrawerForm
				form={editForm}
				onOpenChange={setIsEdit}
				title="编辑用户基础信息"
				open={isEdit}
				onFinish={async (value) => {
					console.log(
						'🚀 ~ This is a result of console.log ~ ✨: value',
						value,
					);
					// message.success('提交成功');
					const res = await update(value);
					if (res.status !== 200) {
						return message.error(res.message || '更新失败');
					}
					message.success('更新成功');
					setFilterCondition({ ...FILTER_CONDITION });

					console.log('res-----------', res);

					return true;
				}}
			>
				<ProForm.Group>
					<Form.Item name="cover">
						<AvatarCom onChange={() => {}} />
					</Form.Item>
				</ProForm.Group>

				<ProForm.Group>
					<ProFormText width="md" name="id" label="人员ID" disabled />
					<ProFormText width="md" name="primary_id" label="用户编号" disabled />
				</ProForm.Group>

				<ProForm.Group>
					<ProFormText width="md" name="name" label="用户姓名" disabled />
					<ProFormText
						width="md"
						name="nickname"
						label="用户昵称"
						tooltip="最长为 10 位"
						placeholder="请输入昵称"
						rules={[
							{
								min: 0,
								max: 10,
							},
						]}
					/>
				</ProForm.Group>
				<ProForm.Group>
					<ProFormText
						width="md"
						name="province"
						label="省"
						placeholder="请输入名称"
					/>
					<ProFormText
						width="md"
						name="city"
						label="市 "
						placeholder="请输入名称"
					/>
				</ProForm.Group>
				<ProForm.Group>
					<ProFormSelect
						options={[
							{
								value: 'normal',
								label: '普通用户',
							},
							{
								value: 'vip',
								label: 'vip用户',
							},
							{
								value: 'shop',
								label: '商家',
							},
						]}
						width="sm"
						name="role"
						label="用户角色"
					/>
					<ProFormSelect
						options={[
							{
								value: 'man',
								label: '男',
							},
							{
								value: 'female',
								label: '女',
							},
						]}
						width="sm"
						name="sex"
						label="性别"
					/>
					<Form.Item name="age" label="年龄">
						<InputNumber />
					</Form.Item>
					<Form.Item name="account" label="账户金额">
						<InputNumber />
					</Form.Item>
				</ProForm.Group>
				<Form.Item name="description" label="个人描述">
					<TextArea
						placeholder="用一句话形容自己吧"
						showCount
						maxLength={100}
					/>
				</Form.Item>
			</DrawerForm>
		</div>
	);
};

export default Vip;
